package webserver.core;

import webserver.http.HttpServleResponse;
import webserver.http.HttpServletRequest;

import java.io.File;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class DispatcherServlet {
    //表示sources下的static目录.实际是编译后的target/classes下的static目录 。
    private static File staticDir;
    static {
        try {
            staticDir= new File(
                    ClientHandler.class.getClassLoader().getResource(
                            "./static"
                    ).toURI()
            );
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    public void service(HttpServletRequest request, HttpServleResponse response){
        String path = request.getUri();
        System.out.println("请求路径:"+path);


        File file1=new File(staticDir,path);



        if(file1.isFile()){
            String []name=file1.getName().split(".");
            Map<String,String> map=new HashMap<>();

            map.put("html","text/html");
            map.put("css","text/css");
            map.put("js","application/javascript");
            map.put("png"," image/png");
            map.put("gif ","image/gif");
            map.put("jpg  ","image/jpeg");
            response.setContentFile(file1);
            response.addHeader("Content-Type",map.get(name[1])+"");
            response.addHeader("Content-Length", file1.length()+"");
        }else{
            response.setStatuseCode(404);
            response.setStatusReason("NOtFound");
            file1=new File(staticDir,"/root/404.html");
            response.setContentFile(file1);

        }
    }
}
